package main

import (
	"database/sql"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"os"
)

var SaasYcgDb *gorm.DB

func init() {
	SaasYcgDb = connectYcg()
}

func connectYcg() *gorm.DB {
	var err error
	//连接数据库
	//SaasYcgDb, err = gorm.Open("mysql", "8bc6dd9b-8f37-43db-b9c1-5d01db10066d:g260fR6KUx4yXNfz@tcp(audit.mingyuanyun.com:30208)/gfyx_ycg?charset=utf8mb4&parseTime=true")
	//dsn := fmt.Sprintf("wengg01@292:718c17e736f7795e546ef3e89fe96257@(dbproxy.mysre.cn:13366)/gfyx_ycg?charset=utf8mb4&parseTime=true") //生产环境
	dsn := fmt.Sprintf("root:E8aisygkcvT3@(rm-wz9yi3c0jl9n118938o.mysql.rds.aliyuncs.com:3306)/gfyx_ycg?charset=utf8mb4&parseTime=true") //测试环境
	//dsn := fmt.Sprintf("root:qziCSjIG3HGtdoXx@(rm-uf670dh81953650b55o.mysql.rds.aliyuncs.com:3306)/gfyx_ycg?charset=utf8mb4&parseTime=true") //预发布环境
	SaasYcgDb, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
	}
	fmt.Println("数据库连接成功")

	SaasYcgDb = SaasYcgDb.Debug()

	return SaasYcgDb
}

type profitInfo struct {
	Id              int64 `gorm:"primary_key"`
	ProfitCode      string
	StartTime       sql.NullTime
	EndTime         sql.NullTime
	Number          int32
	DeliveryBatchNo string
	DeliveryNo      string
	DeliveryAuthId  string
	ProfitGuid      string
	CreatedOn       sql.NullTime // 创建时间
	CreatedBy       string       // 创建人
	ModifiedOn      sql.NullTime // 更新时间
	ModifiedBy      string       // 更新人
	IsDeleted       int32        // 是否删除，0：否，1：是
}

type tenantInfo struct {
	Name    string `json:"name"`
	Code    string `json:"code"`
	Enabled string `json:"enabled"`
}

// go run jobs/db.go

func main() {
	sqlText := ""
	errText := ""
	tenantList := make([]tenantInfo, 0)
	err := SaasYcgDb.Table("tenant_config_service.tenant").Find(&tenantList).Error
	if err != nil {
		errText += err.Error() + "\n"
		fmt.Printf("查询租户数据,err:%s", err.Error())
	}

	for _, v := range tenantList {
		tenantDb := "gfyx_" + v.Code
		profitList := make([]profitInfo, 0)
		err := SaasYcgDb.Table(tenantDb + "." + "gfyx_profit").Find(&profitList).Error
		if err != nil {
			errText += v.Code + "," + err.Error() + "\n"
			fmt.Printf("查询租户权益,err:%s", err.Error())
		}

		for _, item := range profitList {
			sqlText += fmt.Sprintf("INSERT INTO  `%s`.`tenants_profit` (`tenant_code`, `profit_name`, `profit_code`, `start_time`, `end_time`, `number`, `delivery_batch_no`, `delivery_no`, `delivery_auth_id`, `profit_guid`, `created_by`, `created_on`, `modified_by`, `modified_on`, `is_deleted`)"+
				" values ('%s','%s','%s','%s','%s','%d','%s','%s','%s','%s','%s','%s','%s','%s','%d');"+"\n", "tenant_config_service", v.Code, getProfitName(item.ProfitCode), item.ProfitCode, item.StartTime.Time.String()[0:19], item.EndTime.Time.String()[0:19], item.Number, item.DeliveryBatchNo, item.DeliveryNo, item.DeliveryAuthId, item.ProfitGuid, item.CreatedBy, item.CreatedOn.Time.String()[0:19], item.ModifiedBy, item.ModifiedOn.Time.String()[0:19], item.IsDeleted)

			fmt.Print("-----", item.ProfitCode)
		}

		if len(profitList) > 0 {
			sqlText += "\n\n"
		}

	}
	//fmt.Println("---------", sqlText)

	outputFile(sqlText, "tenants_profit.sql")
	outputFile(errText, "err.sql")
}

func getProfitName(code string) string {
	name := ""
	if code == "MarketReport" {
		name = "市场洞察"
	} else if code == "ClueRadarProvince" {
		name = "线索雷达省份版"
	} else if code == "ClueRadarNationwide" {
		name = "线索雷达全国版"
	} else if code == "UserAccount" {
		name = "单独账户购买"
	} else if code == "AIOutbound" {
		name = "AI外呼系统"
	} else if code == "YcgMemberAccount" {
		name = "云采购平台会员"
	}
	return name
}

func outputFile(str string, fileName string) {
	fileName = "./jobs/" + fileName
	dstFile, err := os.Create(fileName)
	if err != nil {
		fmt.Println(err.Error())
	}
	if dstFile != nil {
		defer dstFile.Close()
		dstFile.WriteString(str)
	}

}
